package com.ben.utils.sound;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.SparseIntArray;

/**
 * @Author bin.yang
 * @Maintainer bin.yang
 * @date 2019/4/2 17:06
 * Copyright Inc. All rights reserved.
 * desc 小音频播放器
 */
public class SoundPoolUtils {

    private int mStreamVolume;
    private SoundPool mSoundPool;
    private SparseIntArray mPoolMap;
    private int streamId;
    private int playId;

    public static SoundPoolUtils getInstance() {
        return SingleHolder.INSTANCE;
    }

    private static class SingleHolder {
        public static final SoundPoolUtils INSTANCE = new SoundPoolUtils();
    }

    private SoundPoolUtils() {

    }

    public void init(Context context) {
        if (context == null) {
            return;
        }
        if (null == mSoundPool) {
            mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
            mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                @Override
                public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                    play(streamId, 0);
                }
            });
            mPoolMap = new SparseIntArray();
            // 获得声音设备和设备音量
            AudioManager mgr = (AudioManager) context.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
            mStreamVolume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
        }
    }

    /**
     * 加载音频资源
     *
     * @param id    指定当前音频资源用于播放的id
     * @param resId 当前音频资源的id
     */
    public void loadAndPlay(Context context, int id, int resId) {
        mPoolMap.put(id, mSoundPool.load(context, resId, 1));
        streamId = mPoolMap.get(id);
    }

    /**
     * 播放音频资源
     *
     * @param streamId 需要播放的资源对应的id
     * @param loop     是否循环播放 1: 循环； 0：不循环
     */
    private void play(int streamId, int loop) {
        if (null != mSoundPool) {
            playId = mSoundPool.play(streamId, mStreamVolume, mStreamVolume, 1, loop, 1);
        }
    }

    /**
     * 停止当前正在播放的音频资源
     */
    public void stop() {
        if (null != mSoundPool) {
            mSoundPool.stop(playId);
        }
    }

    /**
     * 释放资源
     */
    public void release() {
        if (null != mSoundPool) {
            mSoundPool.release();
            mSoundPool = null;
        }
    }
}
